<template>
  <div class="article-edit-container">
    <a-page-header
      title="编辑文章"
      sub-title="精雕细琢，打造优质内容"
      @back="handleBack"
      class="page-header"
    />

    <div class="edit-content">
      <a-spin :spinning="loading">
        <a-form
          ref="formRef"
          :model="articleForm"
          :rules="formRules"
          layout="vertical"
          class="article-form"
        >
          <!-- 文章标题区域 -->
          <div class="form-section">
            <div class="section-header">
              <h3 class="section-title">
                <span class="section-icon">📝</span>
                文章标题
              </h3>
              <p class="section-desc">为你的文章取一个简洁有力的标题</p>
            </div>
            <a-form-item name="title" required>
              <a-input
                v-model:value="articleForm.title"
                placeholder="请输入文章标题，建议20字以内"
                :maxlength="100"
                show-count
                class="title-input enhanced-input"
                size="large"
              >
                <template #prefix>
                  <EditOutlined class="input-icon" />
                </template>
              </a-input>
            </a-form-item>
          </div>

          <!-- 文章内容区域 -->
          <div class="form-section content-section">
            <div class="section-header">
              <h3 class="section-title">
                <span class="section-icon">🎯</span>
                文章内容
              </h3>
              <p class="section-desc">支持Markdown语法，实时预览效果</p>
            </div>
            <a-form-item name="content" required>
              <div class="editor-wrapper">
                <div class="editor-toolbar">
                  <div class="toolbar-info">
                    <InfoCircleOutlined />
                    <span>支持拖拽上传图片，Ctrl+S 快速保存</span>
                  </div>
                </div>
                <div class="markdown-editor-container enhanced-editor">
                  <v-md-editor
                    v-model="articleForm.content"
                    height="800px"
                    :disabled-menus="[]"
                    :include-level="[1, 2, 3, 4, 5, 6]"
                    @upload-image="handleImageUpload"
                    @save="handleSaveContent"
                    @change="handleContentChange"
                    placeholder="开始创作你的精彩内容...&#10;&#10;支持Markdown语法：&#10;- **加粗文字**&#10;- *斜体文字*&#10;- # 标题&#10;- ```代码块```&#10;- [链接文字](链接地址)"
                  />
                </div>
              </div>
            </a-form-item>
          </div>

          <!-- 文章属性区域 -->
          <div class="form-section meta-section">
            <div class="section-header">
              <h3 class="section-title">
                <span class="section-icon">🏷️</span>
                文章属性
              </h3>
              <p class="section-desc">设置文章的分类、标签和摘要信息</p>
            </div>
            
            <a-row :gutter="32">
              <a-col :span="24">
                <a-form-item label="文章摘要" name="summary" required>
                  <a-textarea
                    v-model:value="articleForm.summary"
                    placeholder="用简洁的语言描述文章的核心内容，让读者快速了解文章要点..."
                    :maxlength="500"
                    show-count
                    :rows="3"
                    class="summary-textarea enhanced-textarea"
                  >
                    <template #prefix>
                      <FileTextOutlined class="textarea-icon" />
                    </template>
                  </a-textarea>
                </a-form-item>
              </a-col>
            </a-row>

            <a-row :gutter="32">
              <a-col :span="12">
                <a-form-item label="文章分类" name="categoryId" required>
                  <a-select
                    v-model:value="articleForm.categoryId"
                    placeholder="选择最适合的分类"
                    class="category-select enhanced-select"
                    size="large"
                  >
                    <a-select-option
                      v-for="category in categories"
                      :key="category._id || category.id"
                      :value="category._id || category.id"
                    >
                      <span class="category-option">
                        <FolderOutlined class="option-icon" />
                        {{ category.name }}
                      </span>
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="文章标签" name="tagIds">
                  <a-select
                    v-model:value="articleForm.tagIds"
                    mode="multiple"
                    placeholder="选择相关标签（最多5个）"
                    :max-tag-count="5"
                    class="tag-select enhanced-select"
                    size="large"
                  >
                    <a-select-option
                      v-for="tag in tags"
                      :key="tag._id || tag.id"
                      :value="tag._id || tag.id"
                    >
                      <span class="tag-option">
                        <TagOutlined class="option-icon" />
                        {{ tag.name }}
                      </span>
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
          </div>

          <!-- 发布设置区域 -->
          <div class="form-section publish-section">
            <div class="section-header">
              <h3 class="section-title">
                <span class="section-icon">🚀</span>
                发布设置
              </h3>
              <p class="section-desc">选择文章发布状态</p>
            </div>
            <a-form-item name="status" required>
              <a-radio-group 
                v-model:value="articleForm.status" 
                class="status-radio-group enhanced-radio"
              >
                <a-radio-button value="draft" class="radio-draft">
                  <SaveOutlined />
                  草稿
                  <span class="radio-desc">保存为草稿，稍后继续编辑</span>
                </a-radio-button>
                <a-radio-button value="published" class="radio-publish">
                  <CheckCircleOutlined />
                  发布
                  <span class="radio-desc">立即发布文章，对外可见</span>
                </a-radio-button>
              </a-radio-group>
            </a-form-item>
          </div>

          <!-- 操作按钮区域 -->
          <div class="form-actions">
            <a-form-item>
              <div class="action-buttons">
                <a-tooltip title="保存更改并返回文章列表">
                  <a-button
                    type="primary"
                    :loading="saving"
                    @click="handleUpdate"
                    class="action-btn update-btn"
                    size="large"
                  >
                    <CheckOutlined />
                    更新文章
                  </a-button>
                </a-tooltip>

                <a-tooltip title="放弃编辑，返回文章列表">
                  <a-button
                    @click="handleBack"
                    class="action-btn cancel-btn"
                    size="large"
                  >
                    <CloseOutlined />
                    取消编辑
                  </a-button>
                </a-tooltip>
              </div>
            </a-form-item>
          </div>
        </a-form>
      </a-spin>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { message } from 'ant-design-vue'
import { useRouter, useRoute } from 'vue-router'
import VMdEditor from '@kangc/v-md-editor'
import '@kangc/v-md-editor/lib/style/base-editor.css'
import githubTheme from '@kangc/v-md-editor/lib/theme/github.js'
import '@kangc/v-md-editor/lib/theme/style/github.css'

// 引入highlight.js
import hljs from 'highlight.js'
import 'highlight.js/styles/github.css'

// 配置主题
VMdEditor.use(githubTheme, {
  Hljs: hljs,
})

// 全局错误处理
window.addEventListener('error', (e) => {
  if (e.message.includes('ResizeObserver loop limit exceeded') || 
      e.message.includes('ResizeObserver loop completed with undelivered notifications')) {
    e.stopImmediatePropagation()
    return false
  }
})

import articleApi from '@/api/article'
import categoryApi from '@/api/category'
import tagApi from '@/api/tag'
import imageApi from '@/api/image'

const router = useRouter()
const route = useRoute()
const formRef = ref()
const loading = ref(false)
const saving = ref(false)
const categories = ref([])
const tags = ref([])

// 文章表单数据
const articleForm = reactive({
  title: '',
  summary: '',
  content: '',
  contentHtml: '',
  categoryId: null,
  tagIds: [],
  status: '' // 初始化为空，等待从服务器获取
})

// 表单验证规则 - 为内容添加自定义验证
const formRules = {
  title: [
    { required: true, message: '请输入文章标题', trigger: 'blur' },
    { min: 1, max: 100, message: '标题长度应在1-100个字符之间', trigger: 'blur' }
  ],
  summary: [
    { required: true, message: '请输入文章摘要', trigger: 'blur' },
    { min: 1, max: 500, message: '摘要长度应在1-500个字符之间', trigger: 'blur' }
  ],
  content: [
    { 
      required: true, 
      validator: (rule, value, callback) => {
        if (!value || value.trim().length === 0) {
          callback(new Error('请输入文章内容'))
        } else if (value.trim().length < 1) {
          callback(new Error('文章内容不能少于1个字符'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  categoryId: [
    { required: true, message: '请选择文章分类', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择文章状态', trigger: 'change' }
  ]
}
// 获取文章详情
const fetchArticleDetail = async () => {
  const articleId = route.params.id
  if (!articleId) {
    message.error('文章ID无效')
    router.push('/articles')
    return
  }

  loading.value = true
  try {
    const response = await articleApi.getArticleDetail(articleId)
    if (response.code === 200) {
      const article = response.data
      console.log('文章详情:', article) // 调试日志
      console.log('文章状态字段 status:', article.status) // 调试状态字段

      // 设置表单数据
      articleForm.title = article.title || ''
      articleForm.summary = article.summary || ''
      articleForm.content = article.content || ''
      articleForm.contentHtml = article.contentHtml || ''
      articleForm.categoryId = article.categoryId || article.category?.id || null
      if(Array.isArray(article.tags)){
        articleForm.tagIds = article.tags.map(tag => tag.id || null) || []
      }else{
        articleForm.tagIds = []
      }

      // 确保状态正确设置
      // 如果文章有状态字段，使用它；否则默认为 draft
      if (article.status) {
        articleForm.status = article.status
      } else if (article.state) {
        articleForm.status = article.state
      } else {
        articleForm.status = 'draft'
      }

      console.log('最终设置的状态:', articleForm.status) // 调试日志

      // 等待下拉框数据加载完成后再设置值
      await nextTick()
    } else {
      message.error('获取文章详情失败')
      router.push('/articles')
    }
  } catch (error) {
    console.error('获取文章详情失败:', error)
    message.error('获取文章详情失败')
    router.push('/articles')
  } finally {
    loading.value = false
  }
}

// 获取分类列表
const fetchCategories = async () => {
  try {
    const response = await categoryApi.getCategories()
    if (response.code === 200 && response.data) {
      // Handle both direct data and nested data structure
      const data = response.data.data || response.data
      categories.value = Array.isArray(data) ? data : []
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
    message.error('获取分类列表失败')
  }
}

// 获取标签列表
const fetchTags = async () => {
  try {
    const response = await tagApi.getTags()
    if (response.code === 200) {
      tags.value = response.data
    }
  } catch (error) {
    console.error('获取标签列表失败:', error)
    message.error('获取标签列表失败')
  }
}

// 返回上一页
const handleBack = () => {
  router.back()
}

// 图片上传处理 - 上传到服务器
const handleImageUpload = async (event, insertImage) => {
  const file = event.target.files[0]
  if (!file) return

  // 检查文件类型
  if (!file.type.startsWith('image/')) {
    message.error('请选择图片文件')
    return
  }

  // 检查文件大小 (最大10MB)
  if (file.size > 10 * 1024 * 1024) {
    message.error('图片大小不能超过10MB')
    return
  }

  try {
    // 显示上传中的提示
    const hide = message.loading('图片上传中...', 0)

    // 创建FormData对象
    const formData = new FormData()
    formData.append('file', file)
    formData.append('name', file.name)
    formData.append('category', 'article') // 文章图片分类

    // 上传图片
    const response = await imageApi.uploadImage(formData)

    hide() // 隐藏加载提示

    if (response.code === 200 && response.data) {
      // 插入图片到编辑器
      insertImage({
        url: response.data.url || response.data.path, // 服务器返回的图片URL
        desc: file.name
      })
      message.success('图片上传成功')
    } else {
      message.error(response.message || '图片上传失败')
    }
  } catch (error) {
    console.error('图片上传失败:', error)
    message.error('图片上传失败')
  }
}

// 保存内容（Ctrl+S）
const handleSaveContent = (text, html) => {
  articleForm.contentHtml = html
  message.success('内容已保存到草稿')
}

// 内容变化时同步更新HTML
const handleContentChange = (text, html) => {
  articleForm.contentHtml = html
}

// 手动验证内容
const validateContent = () => {
  if (!articleForm.content || articleForm.content.trim().length === 0) {
    message.error('请输入文章内容')
    return false
  }
  if (articleForm.content.trim().length < 1) {
    message.error('文章内容不能少于1个字符')
    return false
  }
  return true
}

// 更新文章
const handleUpdate = () => {
  const articleId = route.params.id
  
  // 手动验证内容
  if (!validateContent()) return
  
  formRef.value.validate().then(async () => {
    try {
      saving.value = true
      const articleData = {
        title: articleForm.title,
        summary: articleForm.summary,
        content: articleForm.content,
        contentHtml: articleForm.contentHtml,
        categoryId: articleForm.categoryId,
        tagIds: articleForm.tagIds,
        status: articleForm.status
      }

      console.log('Updating article with data:', articleData)
      console.log('Article status:', articleForm.status)

      // 先更新文章内容
      const response = await articleApi.updateArticle(articleId, articleData)
      if (response.code === 200) {
        // 再更新文章状态
        const statusResponse = await articleApi.updateArticleStatus(articleId, articleForm.status)
        if (statusResponse.code === 200) {
          message.success(`文章更新成功！状态：${articleForm.status === 'published' ? '已发布' : '草稿'}`)
          router.push('/articles')
        } else {
          message.error('更新文章状态失败')
        }
      } else {
        message.error(response.message || '更新失败')
      }
    } catch (error) {
      console.error('更新文章失败:', error)
      message.error('更新文章失败')
    } finally {
      saving.value = false
    }
  }).catch(() => {
    message.error('请检查表单填写是否正确')
  })
}


// 初始化
onMounted(async () => {
  // 先加载分类和标签数据
  await Promise.all([fetchCategories(), fetchTags()])
  // 再加载文章详情，这样可以正确匹配选中的分类和标签
  await fetchArticleDetail()
})
</script>

<style scoped>
.article-edit-container {
  padding: 24px;
  animation: fadeIn 0.5s ease-out;
}

.page-header {
  margin-bottom: 24px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.09);
  padding: 20px 24px;
}

.page-header :deep(.ant-page-header-heading-title) {
  color: #262626;
  font-weight: 500;
  font-size: 24px;
}

.page-header :deep(.ant-page-header-heading-sub-title) {
  color: #666;
  font-size: 14px;
}

.edit-content {
  max-width: 1600px;
  margin: 0 auto;
}

.article-form {
  max-width: 100%;
}

/* 分区卡片样式 */
.form-section {
  background: white;
  border-radius: 8px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.09);
  border: 1px solid rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.form-section:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
}

.section-header {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.section-title {
  display: flex;
  align-items: center;
  margin: 0 0 8px 0;
  font-size: 18px;
  font-weight: 500;
  color: #262626;
}

.section-icon {
  font-size: 20px;
  margin-right: 8px;
}

.section-desc {
  margin: 0;
  color: #666;
  font-size: 14px;
}

/* 输入框样式 */
.enhanced-input {
  border-radius: 6px;
  border: 1px solid #d9d9d9;
  transition: all 0.3s ease;
  font-size: 14px;
  height: 40px;
}

.enhanced-input:hover {
  border-color: #1890ff;
}

.enhanced-input:focus {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.input-icon {
  color: #1890ff;
  font-size: 16px;
}

/* 文本域样式 */
.enhanced-textarea {
  border-radius: 6px;
  border: 1px solid #d9d9d9;
  transition: all 0.3s ease;
  font-size: 14px;
  line-height: 1.6;
}

.enhanced-textarea:hover {
  border-color: #1890ff;
}

.enhanced-textarea:focus {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.textarea-icon {
  color: #1890ff;
  margin-right: 8px;
}

/* 选择器样式 */
.enhanced-select {
  border-radius: 6px;
  border: 1px solid #d9d9d9;
  transition: all 0.3s ease;
}

.enhanced-select:hover {
  border-color: #1890ff;
}

.enhanced-select:focus {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.category-option,
.tag-option {
  display: flex;
  align-items: center;
}

.option-icon {
  margin-right: 8px;
  color: #1890ff;
}

/* 编辑器区域样式 */
.content-section {
  margin-bottom: 24px;
}

.editor-wrapper {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #d9d9d9;
  transition: all 0.3s ease;
}

.editor-wrapper:hover {
  border-color: #1890ff;
}

.editor-toolbar {
  padding: 12px 16px;
  background: #fafafa;
  border-bottom: 1px solid #f0f0f0;
}

.toolbar-info {
  display: flex;
  align-items: center;
  color: #666;
  font-size: 13px;
}

.toolbar-info span {
  margin-left: 8px;
}

.enhanced-editor {
  border: none;
  border-radius: 0;
}

/* 单选按钮样式 */
.enhanced-radio {
  display: flex;
  gap: 16px;
}

.enhanced-radio :deep(.ant-radio-button-wrapper) {
  height: auto;
  padding: 12px 20px;
  border-radius: 6px;
  border: 1px solid #d9d9d9;
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  min-width: 100px;
}

.enhanced-radio :deep(.ant-radio-button-wrapper:hover) {
  border-color: #1890ff;
  color: #1890ff;
}

.enhanced-radio :deep(.ant-radio-button-wrapper-checked) {
  border-color: #1890ff;
  background: #e6f7ff;
  color: #1890ff;
}

.enhanced-radio :deep(.ant-radio-button-wrapper-checked::before) {
  background: #1890ff;
}

.radio-desc {
  display: block;
  font-size: 12px;
  color: #666;
  margin-top: 4px;
}

/* 操作按钮区域 */
.form-actions {
  background: white;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.09);
  border-top: 1px solid #f0f0f0;
}

.action-buttons {
  display: flex;
  gap: 16px;
  justify-content: center;
  flex-wrap: wrap;
}

.action-btn {
  min-width: 120px;
  height: 40px;
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.update-btn {
  background: linear-gradient(135deg, #1890ff 0%, #40a9ff 100%);
  border: none;
  color: white;
}

.update-btn:hover:not(:disabled) {
  background: linear-gradient(135deg, #40a9ff 0%, #69c0ff 100%);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);
}

.update-btn:active:not(:disabled) {
  transform: translateY(0);
}

.draft-btn {
  border: 1px solid #1890ff;
  color: #1890ff;
}

.draft-btn:hover {
  background: #e6f7ff;
  border-color: #40a9ff;
  transform: translateY(-1px);
}

.cancel-btn {
  border: 1px solid #d9d9d9;
  color: #666;
}

.cancel-btn:hover {
  color: #1890ff;
  border-color: #1890ff;
  transform: translateY(-1px);
}

/* v-md-editor样式优化 */
:deep(.v-md-editor) {
  box-shadow: none;
  border: none;
  border-radius: 0;
  min-height: 500px;
}

:deep(.v-md-editor__editor-wrapper) {
  border-right: 1px solid #f0f0f0;
}

:deep(.v-md-editor__toolbar) {
  background: #fafafa;
  border-bottom: 1px solid #f0f0f0;
  padding: 8px 12px;
}

:deep(.v-md-editor__preview) {
  background: #fafafa;
}

:deep(.v-md-editor__left-area) {
  border-right: 1px solid #f0f0f0;
}

:deep(.v-md-editor__left-area-title) {
  background: #fafafa;
  border-bottom: 1px solid #f0f0f0;
}

/* 动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .article-edit-container {
    padding: 16px;
  }
  
  .form-section {
    padding: 16px;
  }
  
  .personal-info-header h2 {
    font-size: 20px;
  }
  
  .enhanced-radio {
    flex-direction: column;
  }
  
  .enhanced-radio :deep(.ant-radio-button-wrapper) {
    min-width: auto;
    width: 100%;
  }
  
  .action-buttons {
    flex-direction: column;
    gap: 12px;
  }
  
  .action-btn {
    width: 100%;
  }
}
</style>